#!/usr/bin/perl

use strict;
use CGI;
use YAML::Syck;
require 'config.pl';

my $cgi = new CGI;

print "Content-type: text/html\n\n";


if ($cgi->param()) {
        # das Formular wurde abgeschickt, ich kann die Daten verarbeiten und ein Ergebnis anzeigen

        my $board_data = {};
        my $board_name = {};
        my $template_name = {};

        my $post_tmpl = "";
        my $url_tmpl = "";
        my $screenshot_tmpl = "";

        my $screen_block = "";
        my $url_bbcode_block = "";
        my $url_plain_block = "";

        unless($cgi->param('board_name')) {
            print "No Boardname comitted. Exiting.\n";
            exit 0;
        }

        $board_name = $cgi->param('board_name');
        $template_name = $cgi->param('template_name');

        if(-e $::rsspreader_yaml_board_template_dir ."/". $board_name .".yaml"  && !(-z $::rsspreader_yaml_board_template_dir ."/". $board_name .".yaml"))
        {
            $board_data = YAML::Syck::LoadFile($::rsspreader_yaml_board_template_dir ."/". $board_name .".yaml");

            $post_tmpl = $board_data->{$board_name}->{$template_name}->{'post_tmpl'};
            $url_tmpl = $board_data->{$board_name}->{$template_name}->{'url_tmpl'};
            $screenshot_tmpl = $board_data->{$board_name}->{$template_name}->{'screenshot_tmpl'};

            my $posterurl = $cgi->param('posterurl');
            my $rlsname = $cgi->param('rlsname');
            my $nfo = $cgi->param('nfo');

            $post_tmpl =~ s/###posterurl###/$posterurl/;
            $post_tmpl =~ s/###rlsname###/$rlsname/;
            $post_tmpl =~ s/###nfo###/$nfo/;

            foreach my $screenshot (split /\r?\n/, $cgi->param('screenshot_list')){
                $screen_block = $screen_block . "\n" . $screenshot_tmpl;
                $screen_block =~ s/###screenshot###/$screenshot/;
            }

            foreach my $url (split /\r?\n/, $cgi->param('url_list')){
                $url_plain_block = $url_plain_block . "\n" . $url;

                $url_bbcode_block = $url_bbcode_block . "\n" . $url_tmpl;
                $url_bbcode_block =~ s/###url###/$url/;
            }

            $post_tmpl =~ s/###urlblockbbcode###/$url_bbcode_block/;
            $post_tmpl =~ s/###urlblockplain###/$url_plain_block/;
            $post_tmpl =~ s/###screenshotblock###/$screen_block/;

            print $post_tmpl;

            exit 1;
        }
        else
        {
            print "Unknown Boardname. Exiting.";
            exit 0;
        }
}
else {
       # es wurde noch nicht abgeschickt, also muss ich es anzeigen
       print "Required POST-Variables are missing. Exiting.\n";
       exit 0;
}